<!--
 * @Author: anshengtyp
 * @Date: 2024-02-26 17:12:05
 * @LastEditTime: 2024-03-25 09:23:10
 * @LastEditors: anshengtyp
 * @Description:720设置
-->

<template>
  <div class="app-container setting" v-loading="loading" element-loading-text="图片处理中...">
    <div v-show="!addMark" class="left">
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="basicInfo">
          <basicInfo ref="basicInfo" @getFileData="getFileData" @getInfo="getInfo" :newData="infoData"></basicInfo>
        </el-tab-pane>
        <el-tab-pane :disabled="isEdit" label="方位设置" name="orientation">
          <orientation ref="orientation" @getMarkersConfig="getMarkersConfig" :newData="configData"></orientation>
        </el-tab-pane>
        <el-tab-pane :disabled="isEdit" label="位置设置" name="position">
          <position-Handle @getChildernData="getChildernData" :newData="configData"></position-Handle>
        </el-tab-pane>
        <el-tab-pane :disabled="isEdit" label="操作设置" name="controls">
          <controls-Handle ref="controlsHandle" @getMarkersConfig="getMarkersConfig"
            :newData="configData"></controls-Handle>
        </el-tab-pane>
      </el-tabs>
      <div class="btn">
        <el-button v-show="!addMark" @click="clear">重置</el-button>
        <div>
          <el-button v-show="!addMark" :disabled="isEdit" type="primary" @click="addMark = !addMark">添加注记</el-button>
          <el-button v-show="!addMark" type="primary" @click="save">保存数据</el-button>
        </div>
      </div>
    </div>
    <div class="righe">
      <viewHandler @getMarkersData="getMarkersData" :basicData="configData" :markerList="MarkerData"
        :fullImage="fileList" :addMark="addMark" @editAddMark="editAddMark"></viewHandler>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { convertImage } from "../../../utils/panorama-to-cubemap/index";
import { fileUploadMore, compressFiles } from '@/utils/ruoyi';
import { downloadGet } from "../../../utils/request";
import { get720Details, add720, update720, splitImage } from "@/api/720.js";
import basicInfo from "./components/basicInfos.vue";
import orientation from "./components/orientation.vue";
import positionHandle from "./components/positionHandle.vue";
import controlsHandle from "./components/controlsHandle.vue";
import viewHandler from "./components/viewHandler.vue";

export default {
  name: 'Setting720',
  components: {
    basicInfo,
    orientation,
    positionHandle,
    controlsHandle,
    viewHandler,
  },
  data() {
    return {
      activeName: 'basicInfo',
      addMark: false,
      infoData: {},
      loading: false,
      configData: {},
      MarkerData: {},
      fileList: [],
      tileType: '0',
      groupId: ''
    };
  },

  created() {
    this.groupId = this.$route.query.groupId;
    this.getDetails();
  },
  computed: {
    isEdit() {
      return !this.fileList?.length
    }
  },
  methods: {
    async getDetails() {
      this.loading = true;
      if (!this.$route.query?.id) return this.loading = false;
      const res = await get720Details(this.$route.query?.id || '');
      this.tileType = res.data?.pictureType; // 保存瓦片类型
      this.infoData = res.data;
      this.configData = res.data.detailsValue;
      this.MarkerData = res.data.annotation;
      this.loading = false;
    },
    getInfo(data) {
      this.configData.name = data.name;
      this.configData.remark = data.remark;
      this.infoData = data;
    },
    getFileData(file) {
      this.fileList = file;
    },
    getChildernData(data) {
      Object.assign(this.configData, data);
    },
    getMarkersData(data) {
      this.MarkerData = data;
    },
    getMarkersConfig(data) {
      Object.assign(this.configData, data);
    },
    handleClick({ name }) {
      this.activeName = name;
    },
    // 修改状态
    editAddMark(value) {
      this.addMark = value;
    },
    // 平面分割
    async planeSegment(res) {
      let url = res?.fileNames[1] || this.infoData.annex.path;
      const { data } = await splitImage('url=' + url); // 分割图片
      return data;
    },
    // 立体分割
    async stereSegment(res) {
      const options = {
        rotation: 180,
        interpolation: "lanczos",
        outformat: "jpg",
        outtype: "file",
        width: Infinity
      };
      let targetFile = '';
      let target = {}
      if (this.infoData?.thumb) {
        //  下载图片
        targetFile = await downloadGet(import.meta.env.VITE_APP_PIC_BASE_API + this.infoData.thumb.path, this.infoData.thumb);
      } else {
        const index = res.originalFilenames.findIndex(item => item.includes('前端压缩_'));
        target.url = res.fileNames[index];
        target.name = res.originalFilenames[index];
        target.type = res.originalFilenames[index].split('.').at(-1);
        //  下载图片
        targetFile = await downloadGet(import.meta.env.VITE_APP_PIC_BASE_API + target.url, target);
      }
      let imgBlob = URL.createObjectURL(targetFile);
      const x = await convertImage(imgBlob, options);
      const { fileNames } = await fileUploadMore(x);
      // 分割
      let result = fileNames.map((value) => {
        return 'url=' + value;
      }).join('&');
      const { data } = await splitImage(result);
      let obj = {
        left: fileNames.find(item => item.includes('px_')),
        front: fileNames.find(item => item.includes('nz_')),
        right: fileNames.find(item => item.includes('nx_')),
        back: fileNames.find(item => item.includes('pz_')),
        top: fileNames.find(item => item.includes('py_')),
        bottom: fileNames.find(item => item.includes('ny_'))
      }
      return {
        obj,
        data
      }
    },
    // 提交数据
    async save() {
      const basicInfo = this.$refs.basicInfo.$refs.ruleForms // 基本信息
      if (!this?.fileList?.length) return ElMessage.error('请先上传全景照片！');
      if (typeof this.MarkerData === 'string') {
        this.MarkerData = JSON.parse(this.MarkerData);
      }
      Promise.all([basicInfo].map(this.getFormPromise)).then(async res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
          this.loading = true;
          let params = {
            groupId: this.groupId,
            id: this.infoData?.id || '',
            name: this.infoData.name,
            remark: this.infoData.remark,
            pictureType: this.infoData.pictureType,
            annexId: this.fileList[0]?.annexId,
            thumbId: this.infoData?.thumbId,
            tilesValue: this.infoData?.tilesValue,
            cubeValue: this.infoData.cubeValue,
            cubeTilesValue: this.infoData.cubeTilesValue,
            detailsValue: this.configData && Object.keys(this.configData).length > 0 ? this.configData : null,
            annotation: this.MarkerData && Object.keys(this.MarkerData).length > 0 ? JSON.stringify(this.MarkerData) : null,
          }
          let res = null
          // 有材料同时没有上传
          if (this.fileList?.length && !this.fileList[0]?.annexId) {
            const newFile = await compressFiles(this.fileList[0].raw); // 图片压缩
            res = await fileUploadMore([newFile, this.fileList[0]]);
            const index = res.originalFilenames.findIndex(item => item.includes('前端压缩_'));
            params.thumbId = res.attachmentIds[index];
            params.annexId = res.attachmentIds[index + 1];
          }
          // 图片改变
          if (res !== null) {
            params.tilesValue = null; // 滞空处理
            params.cubeTilesValue = null; // 滞空处理
            params.cubeValue = null;
            if (this.infoData.pictureType === '0') {
              params.tilesValue = await this.planeSegment(res);
            } else {
              let result = await this.stereSegment(res);
              params.cubeValue = result.obj
              params.cubeTilesValue = {
                file: result.data
              };
            }
          } else if (this.tileType !== this.infoData?.pictureType) {
            // 瓦片类型改变
            if (this.infoData.pictureType === '0') {
              if (!this.infoData.tilesValue) {
                // 存在分割的图片
                params.tilesValue = await this.planeSegment(res);
              }
            } else {
              // 存在分割的图片
              if (!this.infoData.cubeTilesValue) {
                let result = await this.stereSegment();
                params.cubeValue = result.obj
                params.cubeTilesValue = {
                  file: result.data
                };
              }
            }
          }
          if (this.infoData?.id) {
            const res = await update720(params);
            if (res.code === 200) {
              ElMessage.success('修改成功');
            }
          } else {
            const res = await add720(params);
            if (res.code === 200) {
              ElMessage.success('添加成功');
            }
          }
          this.$tab.closeOpenPage({ path: "/management720", query: { groupId: this.groupId } });
          this.loading = false;
        }
      })
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        })
      })
    },
    clear() {
      this.infoData = {};
      this.infoData.pictureType = '0';
      this.$refs.controlsHandle.clear();
      this.$refs.controlsHandle.clear();
      this.$refs.orientation.clear();
      this.MarkerData = {};
      this.fileList = [];
    }
  },
};
</script>

<style lang="scss" scoped>
.setting {
  display: flex;

  .left {
    width: 500px;
    padding-right: 15px;

    ::v-deep .el-tabs {
      height: 650px;
    }

    .btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .righe {
    flex: 1;
  }
}
</style>
